package com.qf.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Set;

@Component
public class RedisUtil {

    @Autowired
    private JedisPool pool;

    // 增、改.
    public void set(byte[] key,byte[] value){
        Jedis jedis = pool.getResource();
        try {
            //-----------set-------------
            jedis.set(key,value);
            //------------------------
        } finally {
            jedis.close();
        }
    }
    // 增、改并设置生存时间
    public void setAndExpire(byte[] key,byte[] value,int seconds){
        Jedis jedis = pool.getResource();
        try {
            //-----------set-------------
            jedis.set(key,value);
            jedis.expire(key,seconds);
            //------------------------
        } finally {
            jedis.close();
        }
    }

    // get.
    public byte[] get(byte[] key){
        Jedis jedis = pool.getResource();
        try {
            //-----------get-------------
            byte[] value = jedis.get(key);
            return value;
            //------------------------
        } finally {
            jedis.close();
        }
    }

    // getAndExpire.
    public byte[] getAndExpire(byte[] key,int seconds){
        Jedis jedis = pool.getResource();
        try {
            //-----------get-------------
            byte[] value = jedis.get(key);
            jedis.expire(key,seconds);
            return value;
            //------------------------
        } finally {
            jedis.close();
        }
    }

    // expire.
    public void expire(byte[] key,int seconds){
        Jedis jedis = pool.getResource();
        try {
            //-----------expire-------------
            jedis.expire(key,seconds);
            //------------------------
        } finally {
            jedis.close();
        }
    }


    // del.
    public void del(byte[] key){
        Jedis jedis = pool.getResource();
        try {
            //-----------del-------------
            jedis.del(key);
            //------------------------
        } finally {
            jedis.close();
        }
    }

    // keys.
    public Set<byte[]> keys(byte[] pattern){
        Jedis jedis = pool.getResource();
        try {
            //-----------expire-------------
            Set<byte[]> keys = jedis.keys(pattern);
            return keys;
            //------------------------
        } finally {
            jedis.close();
        }
    }

}
